package com.cheng.im.gateway.mq;

import com.alibaba.fastjson2.JSONObject;
import com.cheng.im.common.bean.msg.ProtoMsg;
import com.cheng.im.common.bean.msg.ProtoMsgV1;
import com.cheng.im.common.constants.MQConstants;
import com.cheng.im.gateway.protobuilder.ChatMsgBuilder;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.exception.MQBrokerException;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.remoting.exception.RemotingException;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.messaging.converter.ProtobufMessageConverter;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * mq生产者，系统消息推送到消息队列交由业务服务落盘
 * @author Cheng
 */
@Component
@Slf4j
public class RocketMQProduce {

    @Resource
    private RocketMQTemplate rocketMQTemplate;

    public boolean sendMessage(String top, ProtoMsgV1.Message pkg, String brokerId) {
        log.info("========消息队列:{}==========", top);
        String to = converString(brokerId);
        try {
            Message message = new Message(top+to, brokerId, null, pkg.toByteArray());

            rocketMQTemplate.getProducer().send(message);
        } catch (MQClientException | MQBrokerException | RemotingException | InterruptedException e) {
            log.info("MQ发送出错");
            throw new RuntimeException(e);
        }
        return true;
    }

    public boolean sendMessage(String top, ProtoMsgV1.Message pkg) {
        log.info("========消息队列:{}==========", top);
        try {
            Message message = new Message(top, null, null, pkg.toByteArray());

            rocketMQTemplate.getProducer().send(message);
        } catch (MQClientException | MQBrokerException | RemotingException | InterruptedException e) {
            log.info("MQ发送出错");
            throw new RuntimeException(e);
        }
        return true;
    }

    public void sendToUser(){

    }

    public void sendToUserExceptClient(){

    }

    private String converString(String source){
        return source.replace(".", "-").replace(":", "_");
    }
}
